import otherHelpers from "./others";
import Wait from "./Wait";

const loadedList = [];
const loadingList = {};
const nativeWin = otherHelpers.globalWin;

export default async function dynamicLoadScript(url, reload = false) {
    if (!!nativeWin) {
        if (!reload && loadedList.includes(url)) {
            return;
        } else if (loadingList.hasOwnProperty(url)) {
            return loadingList[url];
        }

        const req = new Promise((resolve, reject) => {
            const script = nativeWin.document.createElement('script');
            script.async = true;
            script.addEventListener('load', resolve);
            script.addEventListener('error', reject);
            script.src = url;
            nativeWin.document.body.append(script);
        });
        loadingList[url] = req;

        await req;

        delete loadingList[url];
        loadedList.push(url);

        await Wait.milliSeconds(85);
    }
}
